<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 分类参数警告提示 -->
      <el-alert title="注意： 只允许为第三级分类设置相关的参数" type="warning" show-icon></el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cataProps"
            @change="cateListChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs 标签页 -->
      <!-- v-model 选中的标签页 name 值 -->
      <!-- tabClick tab 页被选中时触发的事件 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <!-- label 选项卡的标题 -->
        <!-- name 选项卡别名，方便对选项卡进行操作 -->

        <!-- 动态添加参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            plain
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加参数</el-button>
          <el-table :data="manyTableData" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="success"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="setRemove(index, scope.row)"
                >{{ item }}</el-tag>
                <!-- 添加输入按钮框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  type="primary"
                  plain
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="warning"
                  plain
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态添加属性 -->
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            plain
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加属性</el-button>
          <el-table :data="onlyTableData" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="success"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="setRemove(index, scope.row)"
                >{{ item }}</el-tag>
                <!-- 添加输入按钮框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>

                <!-- 添加新属性 -->
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  type="primary"
                  plain
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="warning"
                  plain
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加动态参数 静态属性对话框 -->
      <el-dialog
        :title=" '添加' + textTitle"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addColse"
      >
        <!-- 表单区域 -->
        <el-form :model="addParams" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="addParams.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsHandle">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑动态参数 静态属性对话框 -->
      <el-dialog
        :title=" '修改' + textTitle"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editFormClose"
      >
        <!-- 表单区域 -->
        <el-form
          :model="editParams"
          :rules="editParamsRules"
          ref="editParamsRef"
          label-width="100px"
        >
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="editParams.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParamsHandle">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类数据 分类数据列表
      cateList: [],

      // 级联选择器选中以后的值
      selectCateKeys: [],

      // 级联选择器配置项
      cataProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },

      // tabs 选中的选项
      activeName: 'many',

      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],

      // 控制对话框显示与隐藏
      addDialogVisible: false,

      // 添加动态参数 静态属性
      addParams: {
        attr_name: ''
      },

      // 对话框验证
      addParamsRules: {
        attr_name: [{ required: true, message: '请输入参数信息', trigger: 'blur' }]
      },

      // 控制编辑对话框显示与隐藏
      editDialogVisible: false,

      // 编辑 动态参数 与静态属性
      editParams: {
        attr_name: ''
      },

      // 验证编辑对话框
      editParamsRules: {
        attr_name: [{ required: true, message: '请输入参数信息', trigger: 'blur' }]
      }
    }
  },

  created() {
    this.getCateList()
  },

  methods: {
    // 删除参数事件
    setRemove(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveParams(row)
    },

    // 参数编辑操作
    async saveParams(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParmamsDate()
    },

    // 展示input 输入框
    showInput(Info) {
      Info.inputVisible = true

      // 想在整个DOM元素异步渲染以后，调用某一个方法
      this.$nextTick(() => {
        // 箭头函数无参数可以写（） 或者 _
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // input 失去焦点后，按enter键后触发的事件
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 如果inputvalue 符合需求 就需要发起需求
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      this.saveParams(row)
    },

    // 删除动态参数 静态属性
    async deleteParams(attrid) {
      const confirmRelut = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmRelut !== 'confirm') return this.$message.error('取消了删除')

      const { data: res } = await this.$http.delete(`/categories/${this.cateId}/attributes/${attrid}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParmamsDate()
    },

    // 修改动态参数以及静态参数
    editParamsHandle() {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParams.attr_id}`, {
          attr_name: this.editParams.attr_name,
          attr_sel: this.activeName
        })

        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParmamsDate()
        this.editDialogVisible = false
      })
    },

    // 点击编辑发送请求获取当前分类信息
    // 参数cateInfo 使用scope 传递过来的信息
    async showEditDialog(cateInfo) {
      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes/${cateInfo.attr_id}`, {
        params: {
          attr_sel: this.activeName
        }
      })

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editParams = res.data
      this.editDialogVisible = true
    },

    // 重置关闭编辑对话框信息
    editFormClose() {
      this.$refs.editParamsRef.resetFields()
    },

    // tabs标签选中选项时触发的事件
    tabClick() {
      this.getParmamsDate()
    },

    // 级联选择器选中的值改变以后的信息
    cateListChange() {
      this.getParmamsDate()
    },

    async getParmamsDate() {
      // 控制级联选择器的选择范围
      // 按照需求，只允许为第三级分类设置相关的参数
      // 一级 和 二级 不能够进行设置
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }

      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },

    // 获取商品分类的数据
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },

    // 关闭对话框清除信息
    addColse() {
      this.$refs.addParamsRef.resetFields()
    },

    // 添加动态参数以及静态属性
    addParamsHandle() {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParams.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)

        this.addDialogVisible = false

        this.getParmamsDate()
      })
    }
  },

  computed: {
    // 控制按钮是否可禁用
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },

    // 获取分类参数id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },

    // 控制对话框主题
    textTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 20px;
}
</style>
